import {Component, ViewChild} from '@angular/core';
import {Content, Events, IonicPage, NavController, NavParams} from 'ionic-angular';
import {HttpService} from "../../providers/HttpService";
import {InfoProvider} from "../../providers/InfoProvider";
import { StreamingMedia, StreamingVideoOptions } from '@ionic-native/streaming-media';
import {CommProvider} from "../../providers/CommProvider";

/**
 * Generated class for the StrategyPage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */
@IonicPage()
@Component({
  selector: 'page-strategy',
  templateUrl: 'strategy.html',
})
export class StrategyPage {

    @ViewChild(Content) content: Content;
    user_info: any;
    strategy: string = 'strategy';
    strategy_list: any[] = [];
    lesson_list: any[] = [];
    strategy_count: number = -1;
    lesson_count: number = -1;

    strategy_type: number = 1;
    start: Array<number> = [0, 0];

    videoOptions: StreamingVideoOptions = {
        successCallback: () => { console.log('Video played') },
        errorCallback: (e) => { console.log('Error streaming') },
        orientation: 'landscape'
    };

    constructor(public navCtrl: NavController, public navParams: NavParams,
                private events: Events,
                private httpService: HttpService,
                private infoProvider: InfoProvider,
                private commProvider: CommProvider,
                private streamingMedia: StreamingMedia) {
        this.user_info = this.infoProvider.getUserInfo();
        if (this.infoProvider.isNative()) {
            this.events.subscribe('push:strategy', (data) => {
                console.log('push:strategy:', data);
                if (this.strategy_list.length > 0) {
                    this.strategy_list.unshift(data);
                    this.start[0] = this.strategy_list.length;
                } else {
                    this.getStrategy(0, false).then(res => {
                        if (res.status == 0) {
                            this.strategy_list = res.data.rows;
                            this.start[0] = this.strategy_list.length;
                        }
                    });
                }
            });

            this.events.subscribe('push:lesson', (data) => {
                console.log('push:lesson:', data);
                if (this.lesson_list.length > 0) {
                    this.lesson_list.unshift(data);
                    this.start[1] = this.lesson_list.length;
                } else {
                    this.getLessons(0, false).then(res => {
                        if (res.status == 0) {
                            this.lesson_list = res.data.rows;
                            this.start[1] = this.lesson_list.length;
                        }
                    });
                }
            });
        }
    }

    ionViewDidLoad() {
        console.log('ionViewDidLoad StrategyPage');
    }

    ionViewWillEnter() {
        console.log('ionViewWillEnter StrategyPage');
        if (this.user_info.type > 0) {
            if (this.strategy_type == 1) {
                this.getStrategy(0, false).then(res => {
                    if (res.status == 0) {
                        this.strategy_list = res.data.rows;
                        this.start[0] = this.strategy_list.length;
                    }
                });
            }
            if (this.strategy_type == 2) {
                this.getLessons(0, false).then(res => {
                    if (res.status == 0) {
                        this.lesson_list = res.data.rows;
                        this.start[1] = this.lesson_list.length;
                    }
                });
            }
        }
    }

    ionViewDidEnter() {
        console.log('ionViewDidEnter StrategyPage');
    }

    ionViewWillUnload() {
        this.events.unsubscribe('push:strategy', (data) => {
            console.log('ionViewWillUnload push:strategy:', data);
        });
    }

    getStrategy(start: number = 0, loader: boolean = true): Promise<any> {
        return new Promise(resolve => {
            this.httpService.instance().setUrl('/strategy/getStrategy')
                .setQuery({
                    status: 1,
                    start: start,
                    size: 10,
                    orderKey: 'id',
                    orderVal: 'desc'
                })
                .showLoader(loader)
                .getRequest()
                .then(res => {
                    this.strategy_count = res.data.count;
                    resolve(res);
                });
        });
    }

    getLessons(start: number = 0, loader: boolean = true): Promise<any> {
        return new Promise((resolve, reject) => {
            this.httpService.instance().setUrl('/lesson/getLesson')
                .setQuery({
                    status: 1,
                    start: start,
                    size: 10,
                    orderKey: 'id',
                    orderVal: 'desc'
                })
                .showLoader(loader)
                .getRequest()
                .then(res => {
                    this.lesson_count = res.data.count;
                    resolve(res);
                });
        });
    }

    onSegmentChanged(event) {
        console.log('onSegmentChanged:', event._value);
        this.content.scrollToTop().then(() => {
            if (this.user_info.type > 0) {
                if (event._value == 'strategy') {
                    this.strategy_type = 1;
                } else if (event._value == 'lessons') {
                    this.strategy_type = 2;
                }

                if (this.strategy_type == 1) {
                    this.getStrategy().then(res => {
                        if (res.status == 0) {
                            this.strategy_list = res.data.rows;
                            this.start[0] = this.strategy_list.length;
                        }
                    });
                }
                if (this.strategy_type == 2) {
                    this.getLessons().then(res => {
                        if (res.status == 0) {
                            this.lesson_list = res.data.rows;
                            this.start[1] = this.lesson_list.length;
                        }
                    });
                }
            }
        });
    }

    onRefresh(refresher) {
        if (this.strategy_type == 1) {
            this.start[0] = 0;
            this.getStrategy(this.start[0], false).then(res => {
                if (res.status == 0) {
                    this.strategy_list = res.data.rows;
                    this.start[0] = this.strategy_list.length;
                }
                refresher.complete();
            });
        }
        if (this.strategy_type == 2) {
            this.start[1] = 0;
            this.getLessons(this.start[1], false).then(res => {
                if (res.status == 0) {
                    this.lesson_list = res.data.rows;
                    this.start[1] = this.lesson_list.length;
                }
                refresher.complete();
            });
        }
    }

    onInfinite(infiniteScroll, index) {
        setTimeout(() => {
            if (this.strategy_type == 1) {
                this.getStrategy(this.start[index], false).then(res => {
                    if (res.status == 0) {
                        this.strategy_list = this.strategy_list.concat(res.data.rows);
                        this.start[0] = this.strategy_list.length;
                    }
                    infiniteScroll.complete();
                });
            }
            if (this.strategy_type == 2) {
                this.getLessons(this.start[index], false).then(res => {
                    if (res.status == 0) {
                        this.lesson_list = this.lesson_list.concat(res.data.rows);
                        this.start[1] = this.lesson_list.length;
                    }
                    infiniteScroll.complete();
                });
            }
        }, 200);
    }

    onItemSelected(type: number, data: any) {
        if (type == 1) {
            if (this.infoProvider.isNative()) {
                this.streamingMedia.playVideo(HttpService.sevenVideo + data.video, this.videoOptions);
            } else {
                this.navCtrl.push('VideoPage', {data: data});
            }
        }
    }

    onItemDeleted(type: number, data: any) {
        switch (type) {
          case 0:
            this.closeStrategy(data);
            break;

          case 1:
            this.closeLesson(data);
            break;
        }
    }

    closeStrategy(data: any) {
      this.commProvider.showConfirmAlert('关闭策略', '确定要关闭该策略吗？').then(confirm => {
        if (confirm) {
          this.httpService.instance()
            .setUrl('/strategy/closeStrategy/' + data.id)
            .putRequest()
            .then(res => {
              if (res.status == 0) {
                this.getStrategy().then(res => {
                  if (res.status == 0) {
                    this.strategy_list = res.data.rows;
                    this.start[0] = this.strategy_list.length;
                  }
                });
              }
            });
        }
      });
    }

    closeLesson(data: any) {
      this.commProvider.showConfirmAlert('关闭课程', '确定要关闭该课程吗？').then(confirm => {
        if (confirm) {
          this.httpService.instance()
            .setUrl('/lesson/closeLesson/' + data.id)
            .putRequest()
            .then(res => {
              if (res.status == 0) {
                this.getLessons().then(res => {
                  if (res.status == 0) {
                    this.lesson_list = res.data.rows;
                    this.start[1] = this.lesson_list.length;
                  }
                });
              }
            });
        }
      });
    }

    onGetStrategy(type: number) {
        switch (type) {
            case 1:
                this.navCtrl.push('MemberPage');
                break;

            case 2:
                break;
        }
    }

    onUserLogin() {
        this.navCtrl.push('LoginPage', {guest_login: true});
    }
}
